package com.xunqi.crm.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xunqi.crm.pojo.Role;
import com.xunqi.crm.pojo.User;
import com.xunqi.crm.service.RoleService;
import com.xunqi.crm.service.UserService;
import com.xunqi.crm.tool.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/list")
    public String list(Model model, String usrName,
                       @RequestParam(required = false,defaultValue = "0") Long roleId,
                       @RequestParam(required = false,defaultValue = "1") int pageIndex) {

        Page<User> page = new Page<>();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (usrName != null && !usrName.equals("") && usrName.length()>0){
            wrapper.like("usr_name",usrName);
        }
        if(roleId != 0){
            wrapper.eq("usr_role_id",roleId);
        }
        IPage<User> iPage = userService.selectPage(pageIndex,page.getPageSize(),wrapper);

        List<Role> roles = roleService.findAll();

        page.setCurrPage(pageIndex);
        page.setTotalPages(iPage.getPages());
        page.setTotal(iPage.getTotal());
        page.setRecords(iPage.getRecords());

        model.addAttribute("page",page);
        model.addAttribute("roles",roles);

        model.addAttribute("usrName",usrName);
        model.addAttribute("roleId",roleId);
        return "user/list";
    }
}
